import cv2

video = r'D:\Documents\data\vtest.avi'
cap=cv2.VideoCapture(video)
fgbg=cv2.createBackgroundSubtractorMOG2()
kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
thresh=200
num = 0
while True:
    ret,frame=cap.read()
    if not ret:#没读到当前帧，结束
        break
    else:
        print("-------第{}帧开始------".format(num))
        num += 1

    fgmask = fgbg.apply(frame)
    fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)  # 开运算，去噪点。
    _,fgmask = cv2.threshold(fgmask,30,0xff,cv2.THRESH_BINARY)

    bgImage = fgbg.getBackgroundImage()
    cnts,_=cv2.findContours(fgmask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)# 在二值图像上检测物体轮廓

    count = 0
    for c in cnts:
        area = cv2.contourArea(c)
        if(area < thresh):#区域面积小于指定阈值
            continue
        count += 1
        print("{}的面积为:{}".format(count, area), end="  ")  # 打印出每个前景的面积
        x,y,w,h = cv2.boundingRect(c)
        print("x:{} y:{}".format(x, y))  # 打印坐标

        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)# 在原图上画外接矩形
        cv2.putText(frame, str(count), (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.4, (0, 225, 0), 1)  # 在前景框上标上编号
    cv2.putText(frame, "count:", (5, 20), cv2.FONT_HERSHEY_COMPLEX, 0.6, (0, 255, 0), 1)  # 显示总数
    cv2.putText(frame, str(count), (75, 20), cv2.FONT_HERSHEY_COMPLEX, 0.6, (0, 255, 0), 1)

    print('共检测到：',count,'个目标')
    print("-------第{}帧结束------\n".format(num-1))

    cv2.resizeWindow("frame", 700, 500)#改变窗口大小
    cv2.resizeWindow("fgmask", 700, 500)#改变窗口大小

    cv2.imshow('frame',frame)# 显示每一帧图像
    cv2.imshow('background',bgImage)# 显示背景
    cv2.imshow('fgmask',fgmask)# 显示每一帧图像对应的前景提取结果

    key = cv2.waitKey(30)#每一帧间隔30秒
    if key == 27:#按esc退出
        break

cap.release()
cv2.destroyAllWindows()